﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;

namespace TireService.Web.View
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                
            }

            // Show customers if search result is buffered
            if (Session["SearchResultBuffered"] != null)
            {
                // Instantiate data layer
                TireServiceDB db = new TireServiceDB();

                List<Customer> customers = new List<Customer>();
                customers = (List<Customer>)Session["SearchResultBuffered"];

                ShowCustomerSearch(customers, db);
            }
        }

        /// <summary>
        /// Postback function that updates customer list based on search
        /// </summary>
        protected void gvCustomerSearch_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            // Get values from client
            string[] param = e.Parameters.Split('|');

            // Get search type (0: customerid, 1: name, 2: phone, 3: email, 4: registrationnumber)
            int SearchType = Convert.ToInt32(param[0]);

            // Instantiate data layer
            TireServiceDB db = new TireServiceDB();

            if (SearchType == 0)
            {
                // Search on customerid

                int customerid = Convert.ToInt32(param[1]);

                // Get customer
                Customer customer = db.GetCustomer(customerid);

                if (customer != null)
                {
                    List<Customer> customers = new List<Customer>();
                    customers.Add(customer);

                    ShowCustomerSearch(customers, db);
                }
            }
            if (SearchType == 1)
            {
                // Search on name

                string name = param[1].ToString();

                // Get customers
                List<Customer> customers = db.Customers.Where(p => p.Name.Contains(name)).ToList();

                if (customers.Count > 0)
                {
                    ShowCustomerSearch(customers, db);
                }
            }
            if (SearchType == 2)
            {
                // Search on phone

                string phone = param[1].ToString();

                // Get customers
                List<Customer> customers = db.Customers.Where(p => p.Phone1.Contains(phone) | p.Phone2.Contains(phone)).ToList();

                if (customers.Count > 0)
                {
                    ShowCustomerSearch(customers, db);
                }
            }
            if (SearchType == 3)
            {
                // Search on email
                string email = param[1].ToString();

                List<Customer> customers = db.Customers.Where(p => p.Email.Contains(email)).ToList();

                if (customers.Count > 0)
                {
                    ShowCustomerSearch(customers, db);
                }
            }
            if (SearchType == 4)
            {
                // Search on car registrationnumber

                string registrationnumber = param[1].ToString();

                List<Car> cars = db.Cars.Where(p => p.RegistrationNumber.Contains(registrationnumber)).ToList();

                // Check if any cars found in search
                if (cars.Count > 0)
                {
                    List<Customer> customers = new List<Customer>();

                    foreach (Car car in cars)
                    {
                        Customer customer = db.GetCustomer(car.CustomerId);
                        customers.Add(customer);
                    }

                    ShowCustomerSearch(customers, db);
                }
            }   
        }

        private void UpdateCarStatusOverview()
        {
            lblActive.Text = "";
            lblInActive.Text = "";
            lblNeedsTireChanged.Text = "";
            lblTireChanged.Text = "";
            lblTireMeasured.Text = "";
            lblPlannedTireChange.Text = "";
            lblNeedsTirePickedUp.Text = "";
            lblPlannedTirePickUp.Text = "";
            lblNeedsTireReturned.Text = "";
            lblPlannedTireReturn.Text = "";
        }

        private void ShowCustomerSearch(List<Customer> customers, TireServiceDB db)
        {
            if (customers.Count() == 1)
            {
                // Reset session buffer
                Session["SearchResultBuffered"] = null;
            }
            else
            {
                // Set buffer
                Session["SearchResultBuffered"] = customers;
            }

            var result = from p in customers
                         join y in db.Cars on p.CustomerId equals y.CustomerId into py
                         from z in py.DefaultIfEmpty()
                         select new
                         {
                             p.CustomerId,
                             p.Name,
                             p.City,
                             p.Phone1,
                             p.Phone2,
                             p.Email,
                             z.RegistrationNumber,
                             z.CarId,
                             z.CustomerSubscriptionId
                         };

            gvCustomerSearch.DataSource = result.ToList();
            gvCustomerSearch.DataBind();
        }

        /// <summary>
        /// Function that bind customer servicedrives to gridview
        /// </summary>
        /// <param name="CarId">Id on car</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomerCarService(int CarId, TireServiceDB db)
        {
            // Load planned/past service details
            gvService.DataSource = db.GetCustomerCarService(CarId);
            gvService.DataBind();
        }

        /// <summary>
        /// Function that bind customer tasks to gridview
        /// </summary>
        /// <param name="CarId">Id on car</param>
        /// <param name="db">Connection to database</param>
        private void LoadCustomerTask(int CarId, TireServiceDB db)
        {
            // Load planned/past task details
            gvTask.DataSource = db.GetTasksByCar(CarId);
            gvTask.DataBind();
        }

        /// <summary>
        /// Postback function that updates gridview with services
        /// </summary>
        protected void gvService_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show servicedrives
            LoadCustomerCarService(Convert.ToInt32(e.Parameters), db);
        }

        /// <summary>
        /// Postback function that updates gridview with tasks
        /// </summary>
        protected void gvTask_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show tasks
            LoadCustomerTask(Convert.ToInt32(e.Parameters), db);
        }

        protected void gvTaskDetail_DataSelect(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            ASPxGridView gvTaskDetail = (sender as ASPxGridView);
            gvTaskDetail.DataSource = db.GetTaskDetailsExtendedView(Convert.ToInt32((sender as ASPxGridView).GetMasterRowKeyValue()));
        }
    }
}